package com.tianjipms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianjipms.dao.AccountMapper;
import com.tianjipms.dao.VehicleMapper;
import com.tianjipms.entity.Account;
import com.tianjipms.entity.Bill;
import com.tianjipms.entity.ParkingCount;
import com.tianjipms.entity.Vehicle;
import com.tianjipms.service.AccountService;
import com.tianjipms.service.ParkingService;
import com.tianjipms.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
@Service
@Transactional
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Resource
    private ParkingService parkingService;
    @Resource
    private VehicleMapper vehicleMapper;
    @Resource
    private AccountMapper accountMapper;
    //收付款
    @Override
    public Result updatePriceByUserId(Bill bill, boolean type) {
        //tpye == true 付钱 false 收钱
        if(type){
            Account account = accountMapper.selectById(bill.getUserId());
            if(account.getBalance().compareTo(bill.getPrice()) == -1){
                return Result.error().message("余额不足,请及时充值");
            }else {
                account.setBalance(account.getBalance().subtract(bill.getPrice()));
                accountMapper.updateById(account);
            }
        }else {
            if(bill.getPayeeId() == 0){
                BigDecimal price = bill.getPrice();
                ParkingCount parkingCount = parkingService.findParkingData(20);
                int accountNum = parkingCount.getIsUseVipParkingCount();
                int temp = parkingCount.getIsUseVipParkingCount() + parkingCount.getIsVipParkingCount();
                List<Vehicle> vehicleList = vehicleMapper.findIsUserByVip();
                BigDecimal avgPrice = bill.getPrice().divide(BigDecimal.valueOf(temp));
                for (int i = 0; i < accountNum; i++){
                    Account account = accountMapper.selectById(vehicleList.get(i).getUserId());
                    account.setBalance(account.getBalance().add(avgPrice));
                    accountMapper.updateById(account);
                    price = price.subtract(avgPrice);
                }
                Account account = accountMapper.selectById(1);
                account.setBalance(account.getBalance().add(price));
                accountMapper.updateById(account);
            }else {
                Account account = accountMapper.selectById(bill.getPayeeId());
                account.setBalance(account.getBalance().add(bill.getPrice()));
                accountMapper.updateById(account);
            }

        }
        return Result.ok();
    }
}
